<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" pageName="地点类型">
      <template v-slot:opraCurdBtn1="row">
        <span>
          <el-button type="primary" link size="small" @click="lookBtn(row.row.row)">查看</el-button>
          <el-button type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button type="primary" link size="small" @click="deleteBtn(row.row.row)">删除</el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <el-button class="btn" type="primary" link @click="addBtn('mul')">
          <el-icon style="margin-right: 2px;">
            <svg-icon class-name="search-icon" icon-class="addtotal" />
          </el-icon>新增
        </el-button>
        <el-button class="btn" type="primary" link @click="deleteBtn('mul')">
          <el-icon>
            <DeleteFilled />
          </el-icon>删除
        </el-button>
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto" v-model="state.addModal"
        resize :mask="true">
        <template #title>
          <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="传感器类型" prop="sensorType">
                    <el-select clearable filterable v-model="state.formData.sensorType" placeholder="请选择"
                      @change="sensorTypeChange">
                      <el-option v-for="item in state.typegetSensorsList" :key="item.sensorName"
                        :label="item.sensorName" :value="item.sensorName">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="传感器安装地点" prop="typePlace">
                    <el-input clearable v-model="state.formData.typePlace" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="通风类型" prop="ventilateType">
                    <el-input clearable v-model="state.formData.ventilateType" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="传感器编号" prop="typeCode">
                    <el-select clearable filterable v-model="state.formData.typeCode" multiple placeholder="请选择">
                      <el-option v-for="item in state.typeCodeList" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="报警浓度(%)" prop="alarmValue">
                    <el-input clearable v-model="state.formData.alarmValue" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="断电浓度(%)" prop="cutValue">
                    <el-input clearable v-model="state.formData.cutValue" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="复电浓度(%)" prop="resumeValue">
                    <el-input clearable v-model="state.formData.resumeValue" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="断电范围" prop="cutArea">
                    <el-input clearable v-model="state.formData.cutArea" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="工作面图片上传" prop="imagePath">
                    <el-upload action v-model:file-list="state.fileList"  :before-upload="beforeUpload"
                      :http-request="uploadHttpRequestAdd" ref="upload" list-type="picture"
                      :on-preview="handlePictureCardPreview">
                      <el-button type="primary">
                        <svg-icon class-name="search-icon" icon-class="photo" />上传图片</el-button>
                      <template #tip>
                        <div class="el-upload__tip">
                          上传图片支持jpg/png等，大小不超过 500kb
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="form_footer">
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="submitForm">
                确定
              </el-button>
            </div>
          </div>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 详情 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="40%" close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="dot" /><span>地点类型详情</span></h4>
      </template>
      <p class="drawer_sub_title">
        <svg-icon class-name="search-icon" icon-class="map" /><span>{{state.formData.typePlace}}</span>
      </p>
      <div>
        <el-row :gutter="20">
          <el-col :span="8" style="text-align: center;">
            <div class="img_box">
              <img v-if="state.formData.imagePath !=null" :src="state.formData.imagePath" alt="" />
              <img v-else src="@/assets/images/noimg.png" />
            </div>
          </el-col>
          <el-col :span="16">
            <el-row :gutter="20">
              <el-col :span="8">
                <p>传感器类型</p>
                <p>{{state.formData.sensorType}}</p>
              </el-col>
              <el-col :span="8">
                <p>通风类型</p>
                <p>{{state.formData.ventilateType}}</p>
              </el-col>
              <el-col :span="8">
                <p>传感器编号</p>
                <p>{{state.formData.typeCode}}</p>
              </el-col>
              <el-col :span="8">
                <p>报警浓度(%)</p>
                <p v-if="state.formData.alarmValue">≥{{state.formData.alarmValue}}</p>
                <p v-else>-</p>
              </el-col>
              <el-col :span="8">
                <p>断电浓度(%)</p>
                <p v-if="state.formData.cutValue">≥{{state.formData.cutValue}}</p>
                <p v-else>-</p>
              </el-col>
              <el-col :span="8">
                <p>复电浓度(%)</p>
                <p v-if="state.formData.resumeValue">＜{{state.formData.resumeValue}}</p>
                <p v-else>-</p>
              </el-col>
              <el-col :span="24">
                <p>断电范围</p>
                <p>{{state.formData.cutArea}}</p>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
    <el-dialog v-model="state.dialogVisiblepictureCardPreview">
        <img :src="state.dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import {
    computed,
    reactive
  } from "vue";
  import {
    table_headers
  } from '@/components/commonCom/table_headers';
  import axios from "@/utils/request"
  import usePagesStore from '@/store/modules/pages'
  import {
    gettypeCode,
    fileupload,
    gettypegetSensors
  } from '@/api/config'
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore()
  const upload = ref()
  components: {
    list_controller
  }
  let previewHttps =
    import.meta.env.VITE_APP_HTTP
  let state = reactive({
    dialogVisiblepictureCardPreview:false,
    dialogImageUrl:'',
    fileList:[],
    addModal: false,
    modalTitle: '新增地点类型',
    drawerShow: false,
    // 列表
    options: {
      tableheads: computed(() => table_headers.placeType),
      queryList: {
        dropdownUrl: '',
        querys: [{
          field: 'sensorType',
          title: '传感器类型',
          type: 'select',
          binddata: '',
          options: []
        }, {
          field: 'typePlace',
          title: '地点',
          type: 'input',
          binddata: ''
        }],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/place/type/typesInfo',
      delUrl: '/place/type/deleteType',
      addUrl: '/place/type/addType',
      descUrl: 'place/type/typeInfo/',
      editUrl: '/place/type/editType'
    },
    // 表单
    formRef: null,
    formData: {},
    rules: {
      sensorType: [{
        required: true,
        message: '请选择传感器类型',
        trigger: 'change',
      }],
      typePlace: [{
        required: true,
        message: '请输入传感器安装地点',
        trigger: 'blur'
      }],
      alarmValue: [{
        required: true,
        message: '请输入报警浓度',
        trigger: 'blur'
      }]
    },
    editId: undefined,
    typeCodeList: [],
    typegetSensorsList: []
  })
  // 查看按钮
  function lookBtn(row) {
    state.drawerShow = true
    axios.post(state.options.descUrl + row.id).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        state.typegetSensorsList.forEach(item => {
          if (item.sensorName == state.formData.sensorType) {
            state.typeCodeList = item.sensorCode
          }
        })
      }
    })
  }
  // 新增按钮
  function addBtn(row) {
    state.addModal = true
    state.formData = {}
    state.editId = undefined
    state.fileList=[]
  }
  function LastStr(str) {
    if(str){
      let index = str.lastIndexOf("\/");
      str = str.substring(index + 1, str.length);
      return str;
    }
  }
  // 编辑按钮
  function editBtn(row) {
    state.modalTitle = '编辑地点类型'
    state.addModal = true
    axios.post(state.options.descUrl + row.id).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        state.fileList=[{name:LastStr(state.formData.imagePath),url:state.formData.imagePath}]
        state.typegetSensorsList.forEach(item => {
          if (item.sensorName == state.formData.sensorType) {
            state.typeCodeList = item.sensorCode
            state.formData.typeCode = state.formData.typeCode.split(',')
          }
        })
        state.editId = res.data.id
      }
    })
  }
  function handlePictureCardPreview(uploadFile) {
    state.dialogVisiblepictureCardPreview = true
    state.dialogImageUrl = uploadFile.url
  }
  function deleteBtn(row) {
    let ids = []
    if (row != 'mul') {
      ids = [row.id]
    } else {
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        proxy.$modal.msgSuccess('请先勾选所要删除数据!');
      }
    }
    if (ids.length > 0) {
      axios.post(state.options.delUrl, ids).then(res => {
        if (res.code == 200) {
          proxy.$refs['zujianname'].getData()
          state.addModal = false
          proxy.$modal.msgSuccess(res.msg);
          store.records = []
        }
      })
    }

  }
  /** 提交按钮 */
  function submitForm() {
    if (state.formData.typeCode) {
      state.formData.typeCode = state.formData.typeCode.toString()
    }
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        if (state.editId) {
          state.formData.id = state.editId
          axios.post(state.options.editUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        } else {
          axios.post(state.options.addUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        }
      }
    })
  }

  function cancel() {
    state.addModal = false
  }
  // 下拉选数据
  function getTypeList() {
    let arr = []
    gettypegetSensors().then(res => {
      state.typegetSensorsList = res.data
      res.data.forEach(item => {
        arr.push({
          label: item.sensorName,
          value: item.sensorName
        })
      })
      state.options.queryList.querys[0].options = arr

    })
  }
  const fileType = [
    "jpg", "png", "gif", "jpg", "jpeg"
  ] // 允许的文件类型
  const uploadHttpRequestAdd = (data) => {
    upload.value.clearFiles();
    const formData = new FormData();
    formData.append("file", data.file);
    fileupload(formData).then(res => {
      state.formData.imagePath = previewHttps + res.fileName
      console.log(state.formData.imagePath,'state.formData.imagePath');
      state.fileList.push({url:state.formData.imagePath})
      proxy.$modal.msgSuccess(res.msg);
    })
  }
  const beforeUpload = (file) => { //上传前的钩子
    if (file.type != "" || file.type != null || file.type != undefined) {
      //截取文件的后缀，判断文件类型
      const FileExt = file.name.replace(/.+\./, "").toLowerCase();
      // 计算文件的大小
      const isLt5M = file.size / 1024 < 500; //这里做文件大小限制
      //如果大于500kb
      if (!isLt5M) {
        proxy.$modal.msgWarning("上传文件大小超过限制!");
        upLoading.value = 0
        return false;
      }
      //如果文件类型不在允许上传的范围内
      if (fileType.includes(FileExt)) {
        return true;
      } else {
        proxy.$modal.msgWarning("上传文件格式不正确!");
        upLoading.value = 0
        return false;
      }
    }
  }

  function sensorTypeChange(val) {
    state.typegetSensorsList.forEach(item => {
      if (item.sensorName == val) {
        state.typeCodeList = item.sensorCode
      }
    })
  }
  getTypeList()
</script>
<style lang="scss" scoped>

</style>